package leetcode.weekly.week324;

import java.util.ArrayList;
import java.util.List;

//Solution2Test
public class Solution2 {

	public int smallestValue(int n) {
		List<Integer> list = new ArrayList<>();
		for (int i = 2; i <= n; i++) {
			if (isPrime(i)) {
				list.add(i);
			}
		}
		int last = 0;
		while (!list.contains(n)) {
			int cur = 0;
			int p = 0;
			last = n;
			while (p < list.size() && !list.contains(n) && n > 1) {
				while ((n % list.get(p)) == 0) {
					cur += list.get(p);
					n /= list.get(p);
				}
				p++;
			}
			if (list.contains(n)) {
				cur += n;
			}
			n = cur;
			if (last == n)
				return last;
		}
		return n;
	}

	// 质数
	public boolean isPrime(int num) {
		if (num == 2) {
			return true;
		}
		if (num == 1 || num % 2 == 0) {
			return false;
		}
		for (int i = 3; i * i <= num; i += 2) {
			if (num % i == 0 || i * i == num) {
				return false;
			}
		}
		return true;
	}

}
